<template>
    <div class="container_box">
        <el-scrollbar ref="scrollbarRef" class="main_box">
            <div class="points-settings">
                <div class="content">
                    <el-form ref="formInfoRef" :model="formInfo">
                        <div class="title">会员同步时，积分、成长值合并规则</div>
                        <div class="form">
                            <div class="rules-item">
                                <el-radio v-model="formInfo.radio" label="1">
                                    根据用户在各个渠道的积分、成长值，累加得到该用户的最终积分、成长值
                                </el-radio>
                            </div>
                            <div class="rules-item">
                                <el-radio v-model="formInfo.radio" label="2">
                                    用户在各个渠道的最高分，作为最终积分、成长值
                                </el-radio>
                            </div>
                        </div>
                        <div class="title">
                            全域积分、成长值计算设置<span class="desc">（针对scrm端统一计算积分、成长值的渠道）</span>
                        </div>
                        <div class="form">
                            <div class="label-item">
                                店铺开通会员通，用户成为会员后，参与积分、成长值计算的订单
                                <span class="desc">（*默认按照会员当前等级赠送多倍积分、成长值）</span>
                            </div>
                            <div class="label-item">
                                <el-checkbox :checked="true" disabled> 新产生的已签收订单 （默认开启） </el-checkbox>
                            </div>
                            <div class="label-item">
                                <el-form-item
                                    v-for="(item, index) in formInfo.pointsOrderRuleList"
                                    :key="item.channel_id"
                                    class="point-rule-item"
                                    :prop="`pointsOrderRuleList[${index}]`"
                                    :rules="[{ validator: validateDayNum }]">
                                    <label class="item-checkbox-label">
                                        <el-checkbox v-model="item.switch" :true-label="1" :false-label="2">
                                        </el-checkbox>
                                        {{ item.channel_name }} 最近
                                    </label>
                                    <el-input-number
                                        v-model="item.days"
                                        class="item-day-num"
                                        :disabled="item.switch == 2"
                                        :min="1"
                                        :max="getDayByChannelId(item)"
                                        :controls="false"
                                        :precision="0"
                                        :placeholder="`1~${getDayByChannelId(item)}的整数`"
                                        @blur="handleDayBlur(item)" />
                                    <!-- 自营和线下: xx天内已签收的订单
                                    其余：xx天内已签收或已完成的订单 -->
                                    {{ `天内已签收${[4, 5].includes(item.channel_id) ? '' : '或已完成'}的订单` }}
                                </el-form-item>
                            </div>
                        </div>
                        <div class="title">互动积分转换</div>
                        <div class="form">
                            <div class="rules-item">
                                <div class="form-items">
                                    <div class="form-items-name">互动积分转换会员积分</div>
                                    <div>
                                        <el-switch
                                            v-model="formInfo.exchange_to_member_switch"
                                            class="form-items-header" />
                                        <span class="form-items-tip">开启后，会员可将互动积分转换为会员积分</span>
                                        <div v-show="formInfo.exchange_to_member_switch" class="form-items-item">
                                            <div class="form-items-header">转换规则</div>
                                            每&nbsp;
                                            <el-form-item
                                                prop="exchange_to_member_from_points"
                                                :rules="[{ validator: validatePointNum }]">
                                                <el-input-number
                                                    v-model="formInfo.exchange_to_member_from_points"
                                                    class="form-items-num"
                                                    :min="0"
                                                    :max="1000000"
                                                    :controls="false"
                                                    placeholder="请输入"
                                                    :precision="0" />
                                            </el-form-item>
                                            &nbsp;互动积分可转换为&nbsp;
                                            <el-form-item
                                                prop="exchange_to_member_to_points"
                                                :rules="[{ validator: validatePointNum }]">
                                                <el-input-number
                                                    v-model="formInfo.exchange_to_member_to_points"
                                                    class="form-items-num"
                                                    :min="0"
                                                    :max="1000000"
                                                    :controls="false"
                                                    placeholder="请输入"
                                                    :rules="[{ validator: validatePointNum }]"
                                                    :precision="0" />
                                            </el-form-item>
                                            &nbsp;会员积分
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-form>
                </div>
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { getPointsRuleInfo, setPointsRuleInfo } from '@/api/member/pointsManage/index';
import { ElMessage, ElMessageBox } from 'element-plus';

const formInfoRef = ref<any>(null);

const formInfo = reactive<any>({
    radio: '1',
    newPointsType: true,
    pointsOrderRuleList: [], // 积分、成长值设置渠道列表
    exchange_to_member_switch: null,
    exchange_to_member_from_points: null,
    exchange_to_member_to_points: null
});

// 这里是为了防止中文输入法el-input-number在输入期间点击其他地方会出现异常内容，
const handleDayBlur = (item: any) => {
    item.days = item.days || 1;
};
const validateDayNum = (rule: any, value: any, callback: any) => {
    // switch: 积分、成长值规则开关 1-开启 2-关闭
    const { days, switch: ruleSwich } = value;
    // 校验是否开启
    if (ruleSwich === 2) {
        return callback();
    }
    // 校验是否是正常输入（element-el-input-number在输入期间点击空白处会出现异常内容，这是字段的值会是null）
    const targetDay = getDayByChannelId(value); // 应该输入的最大值
    if (!days) {
        // 注意message是使用一开
        return callback(new Error(`请输入1～${targetDay}的整数`));
    }
    // 校验最大值（虽然正常交互难以出现，但是不确定组件库会不会出bug）
    if (days > targetDay) {
        return callback(new Error(`请输入1～${targetDay}的整数`));
    }
    callback();
};

/**
 * 校验积分数值
 */
const validatePointNum = (rule: any, value: number, callback: any) => {
    if (!formInfo.exchange_to_member_switch) {
        callback();
    }
    switch (rule.field) {
        case 'exchange_to_member_from_points':
            if (!value) {
                callback(new Error(`请输入正整数`));
            }
            break;
        case 'exchange_to_member_to_points':
            if (!value) {
                callback(new Error(`请输入正整数`));
            }
            break;
        default:
            callback();
            break;
    }
    callback();
};

const onSubmit = async () => {
    formInfoRef.value.validate(async (valid: any) => {
        if (valid) {
            ElMessageBox.confirm(`是否确认保存设置？`, '操作提醒', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    const params = {
                        POINTS_MERGE_RULE: {
                            rule: formInfo.radio == '1' ? 'cumulative' : 'maximum'
                        },
                        POINTS_CHANNEL_ORDER_RULE: formInfo.pointsOrderRuleList.map((item: any) => {
                            return {
                                ...item,
                                channel_name: undefined // 过滤后端不需要的字段
                            };
                        }),
                        EXCHANGE_POINTS_RULR: {
                            // 互动积分转换会员积分开关 1 开启 2关闭
                            exchange_to_member_switch: formInfo.exchange_to_member_switch ? 1 : 2,
                            exchange_to_member_from_points: formInfo.exchange_to_member_switch
                                ? formInfo.exchange_to_member_from_points
                                : null,
                            exchange_to_member_to_points: formInfo.exchange_to_member_switch
                                ? formInfo.exchange_to_member_to_points
                                : null
                        }
                    };
                    await setPointsRuleInfo(params);
                    ElMessage.success('设置成功');
                })
                .catch(() => {});
        }
    });
};

const initData = async () => {
    const params = {
        code: [
            'POINTS_GAIN_RULE',
            'POINTS_DRAIN_RULE',
            'POINTS_MERGE_RULE',
            'POINTS_CHANNEL_ORDER_RULE', // 获取对应渠道的积分、成长值设置列表, 原先的POINTS_HISTORY_ORDER_RULE不需要
            'EXCHANGE_POINTS_RULR'
        ]
    };
    const res = await getPointsRuleInfo(params);
    formInfo.radio = res.POINTS_MERGE_RULE.rule == 'cumulative' ? '1' : '2';
    if (Array.isArray(res.POINTS_CHANNEL_ORDER_RULE)) {
        formInfo.pointsOrderRuleList.splice(0);
        // 渠道类型：1-客易达，2-有赞，3-淘宝，4-自营，5-线下门店，6-天猫，7-抖店，8-京东（占坑），9-视频号小店，10-快手小店，抖店最大值是89，其余为90
        formInfo.pointsOrderRuleList.push(...res.POINTS_CHANNEL_ORDER_RULE);
    }
    formInfo.exchange_to_member_switch = res.EXCHANGE_POINTS_RULR.exchange_to_member_switch === 1;
    formInfo.exchange_to_member_from_points = formInfo.exchange_to_member_switch
        ? res.EXCHANGE_POINTS_RULR.exchange_to_member_from_points
        : null;
    formInfo.exchange_to_member_to_points = formInfo.exchange_to_member_switch
        ? res.EXCHANGE_POINTS_RULR.exchange_to_member_to_points
        : null;
};

// 根据渠道获取对应的天数
const getDayByChannelId = (item: any = {}) => {
    return item.channel_id === 7 ? 89 : 90;
};

onMounted(() => {
    initData();
});
</script>
<style lang="scss" scoped>
.points-settings {
    padding: 24px;

    .title {
        font-size: 16px;
        font-weight: 500;
        position: relative;
        padding-left: 15px;
        color: #333;
        margin-top: 20px;

        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            width: 4px;
            height: 16px;
            background-color: var(--el-color-primary);
        }

        &:first-child {
            margin-top: 0;
        }
    }

    .form {
        padding-top: 12px;

        .rules-item {
            padding-left: 14px;
            color: #33302d;
            font-size: 14px;
        }

        .label-item {
            padding-left: 14px;
            color: #33302d;
            font-size: 14px;
            line-height: 40px;

            .day-num {
                margin: 0 8px;
                width: 110px;
            }
        }

        .form-items {
            display: flex;
            align-items: baseline;

            .form-items-name {
                color: #333;
                margin-right: 12px;
            }

            .form-items-header {
                margin-right: 12px;
                color: #333;

                &:first-child {
                    margin-right: 8px;
                }
            }

            .form-items-tip {
                color: #999;
            }

            .form-items-item {
                display: flex;
                align-items: baseline;
            }

            .label {
                display: inline-block;
            }

            .form-items-num {
                width: 90px;
            }
        }
    }

    .desc {
        padding-left: 8px;
        color: #969696;
        font-size: 14px;
        line-height: 14px;
    }

    .footer {
        display: flex;
        justify-content: flex-end;
    }
}

.point-rule-item {
    margin-bottom: 16px;
    font-size: 14px;
    font-family: PingFangSC-Regular, 'PingFang SC';
    font-weight: 400;
    color: #33302d;

    .item-checkbox-label {
        cursor: pointer;
        user-select: none;

        .el-checkbox {
            margin-right: 3px;
            vertical-align: top;
        }
    }

    .item-day-num {
        width: 92px;
        margin-right: 3px;

        :deep(.el-input__wrapper) {
            padding-left: 9px;
            padding-right: 9px;
        }
    }
}

.yz-desc {
    color: #f53f3f;
    font-size: 14px;
}
</style>
